/*
 * lib2Desa - Another 2D game library in C++
 * Copyright (C) 2009 Erivaldo Xavier de Lima Filho
 *
 * This program is free software and is distributed under GNU General Public License version 3. You can modify and/or redistribute
 * it under the terms of GPL version 3 or posterior version. This program comes with NO WARRANTY, for more details, see LICENSE,
 * or <http://www.gnu.org/licenses>.
 *
 * Contact info:
 *
 *	Erivaldo Xavier de Lima Filho, desadoc@gmail.com
 *
 */

#include "Ext/Loaders.hpp"
#include "Core/ISprite.hpp"
#include "Core/Color.hpp"

#include <cstdio>

#include <iostream>
#include <fstream>
#include <list>
using namespace std;

#ifndef _NO_NAMESPACE
namespace lib2Desa {
#endif

const shared_ptr<Animation> load_animation(const char* filename, const shared_ptr<IGraphicDevice>& gd)
{
	char buf[256];
	list<shared_ptr<ISprite> > imgs;
	shared_ptr<ISprite> im;
	shared_ptr<SpriteSequence> ss;
	shared_ptr<FramePicker> fp;
	shared_ptr<Animation> ani;
	list<shared_ptr<ISprite> >::iterator it;
	Color key;

	ifstream in(filename);

	if(!in.is_open()) return shared_ptr<Animation>();

	while(in.good())
	{
		in.getline(buf, 256);
		if(strlen(buf) > 0)
		{
			im = gd->load(buf);
			if(!im) goto fail;
			imgs.push_back(im);
		} else break;
	}

	if(in.bad()) goto fail;

	byte8 R, G, B;
	unsigned val;

	in >> val;
	R = val;
	in >> val;
	G = val;
	in >> val;
	B = val;

	key = Color(R, G, B, 0);

	for(it = imgs.begin(); it != imgs.end(); it++)
	{
		(*it)->setColorKey(key);
	}

	if(in.bad()) goto fail;

	u32 frameRate;
	in >> frameRate;

	in.close();

	ss = new SpriteSequence(imgs.size());

	u32 i;
	it = imgs.begin();

	for(i=0; i<imgs.size();i++)
	{
		ss->set(*it,i);
		it++;
	}

	fp = new FramePicker(ss, frameRate);
	ani = new Animation(fp);

	return ani;

fail:

	in.close();

	for(it = imgs.begin(); it != imgs.end(); it++)
	{
		(*it) = null;
	}

	return shared_ptr<Animation>();
}

#ifndef _NO_NAMESPACE
}
#endif
